<template>
  <!-- 环境数据录入 -->
  <BaseMainSlot :show-tab="true">
    <template v-slot:btn-box>
      <ActionBar
        :page-no="29"
        :has-cancel="false"
        :has-edit="false"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit-column="true"
        :has-export="true"
        :has-del="true"
        @showColumn="showColumn"
        @download="download"
        @add="add"
        @del="handlerDel"
      />
    </template>
    <template v-slot:search-box>
      <SearchForm
        :formConfig="formConfig"
        :formData="searchlist"
        @search="search"
      ></SearchForm>
    </template>
    <template v-slot:table-box>
      <Table
        @sortChange="changeTableSort"
        :propList="tableColumn"
        v-loading="loading"
        :listData="tableData"
        :showSelectColumn="true"
        @handleSelectionChange="handleSelectionChange"
      >
        <template v-slot:operation="{ row }">
          <template v-if="!row.index">
            <el-button
              v-if="row.dataTypeConfigId"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(row)"
              ><i class="el-icon-edit-outline"></i> 编辑</el-button
            >
            <el-button
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="del(row)"
              ><i class="el-icon-delete"></i> 删除</el-button
            >
          </template>
        </template>
      </Table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="textTitle + '环境数据'"
        :visible.sync="dialogFormVisible"
        :before-close="cancel"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          class="el-form"
          :rules="rules"
        >
          <el-form-item class="w50p" label="设施名称" prop="facilityNo">
            <el-select
              v-model="formData.facilityNo"
              clearable
              filterable
              placeholder="请选择设施名称"
            >
              <el-option
                v-for="(item, index) in facilityList"
                :key="index"
                :label="item.facilityName"
                :value="item.facilityNo"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="w50p" label="数据类型" prop="dataTypeConfigId">
            <el-select
              v-if="isInputFlag"
              v-model="formData.dataTypeConfigId"
              clearable
              filterable
              placeholder="请选择物联数据项"
            >
              <el-option
                v-for="(item, index) in dataItemList"
                :key="index"
                :label="item.dataTypeName"
                :value="item.dataTypeConfigId"
              />
            </el-select>
            <el-input v-else v-model="formData.dataTypeNames"></el-input>
          </el-form-item>
          <el-form-item prop="value" class="w50p" label="具体数据">
            <el-input type="number" v-model="formData.value"></el-input>
          </el-form-item>
          <el-form-item class="w50p" label="物联单位" prop="unitNo">
            <el-select
              v-model="formData.unitNo"
              clearable
              filterable
              placeholder="请选择物联单位"
            >
              <el-option
                v-for="(item, index) in unitlist"
                :key="index"
                :label="item.unitName"
                :value="item.unitNo"
              />
            </el-select>
          </el-form-item>
          <!-- :disabled="!dataItemList.length==0" -->
          <!-- <el-form-item class="50p">
            <el-button type="primary" @click="userAdd">手动添加</el-button>
          </el-form-item> -->
          <el-form-item label="录入人:" class="w50p" prop="account">
            <el-select
              v-model="formData.account"
              value-key="personNo"
              filterable
              clearable
            >
              <el-option
                v-for="(item, index) in staffList"
                :key="index"
                :label="item.person.name"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="录入日期:" class="w50p">
            <el-date-picker
              v-model="formData.collectDatetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              type="datetime"
              placeholder="选择投产时间"
              filterable
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">
            取 消
          </el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >
            保 存
          </el-button>
        </div>
      </el-dialog>
      <!-- 列配置 -->
      <el-dialog
        id="tableColumnDialog"
        title="配置列"
        :visible.sync="dialogTableColumnVisible"
      >
        <tableColumn
          v-if="dialogTableColumnVisible"
          ref="tableColumn"
          :tableColumn="allTableColumn"
          @cancelColumn="cancelColumn"
        />
        <div slot="footer" class="dialog-footer">
          <el-button
            class="zh-button-one"
            @click="dialogTableColumnVisible = false"
          >
            取 消
          </el-button>
          <el-button class="zh-button-two" type="primary" @click="saveColumn">
            保 存
          </el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>
  <script>
import danwei from "@/api/basic-info-manage/unit-manage/index";
import SearchForm from "@/components/searchForm";
import Table from "@/components/table/table.vue";
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot.vue";
import { mymixin } from "@/utils/mixin";
import Api from "@/api/digital-production/material-link-monitoring/environmental-data-entry/index";
// 获取执行人
import managementtwo from "@/api/digital-production/agr-input-management/agr-input-managementtwo";
// TODO:
import selectbut from "@/components/selectbutton/index.vue";
import userreq from "@/api/user/index";
export default {
  name: "HistoricalAlarmRecord",
  components: {
    SearchForm,
    Table,
    ActionBar,
    Pagination,
    BaseMainSlot,
    selectbut,
  },
  mixins: [mymixin],
  data() {
    return {
      addActive: true,
      currentPage: 1,
      pageSize: 10,
      totalSize: 1,
      // 设施
      facilityList: [],
      facilityNo: "",
      tableColumn: [
        { prop: "account", label: "录入人", minWidth: "300" },
        { prop: "facilityName", label: "设施名称", minWidth: "300" },
        { prop: "dataTypeName", label: "物联数据名称", minWidth: "150" },
        { prop: "value", label: "具体数据", minWidth: "150" },
        { prop: "unitName", label: "单位", minWidth: "100" },
        { prop: "collectDatetime", label: "录入日期", minWidth: "180" },
        {
          prop: "operation",
          label: "操作",
          slotName: "operation",
          minWidth: "120",
        },
      ],
      formConfig: [
        {
          label: "设施名称",
          prop: "facilityNo",
          type: "select",
          options: [], // facilityList
          optionKey: { label: "facilityName", value: "facilityNo" },
        },
        {
          label: "数据名称",
          prop: "dataName",
          type: "input",
        },
      ],
      dialogFormVisible: false,
      rules: {
        account: [
          {
            required: true,
            message: "录入人不能为空",
            trigger: ["blur", "change"],
          },
        ],
        facilityNo: [
          {
            required: true,
            message: "设施名不能为空",
            trigger: ["blur", "change"],
          },
        ],
        dataTypeConfigId: [
          {
            required: true,
            message: "数据项不能为空",
            trigger: ["blur", "change"],
          },
        ],
        unitNo: [
          {
            required: true,
            message: "单位不能为空",
            trigger: ["blur", "change"],
          },
        ],
        value: [
          {
            required: true,
            message: "具体数据不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
      textTitle: "",
      formData: {
        facilityNo: "",
        dataTypeConfigId: "",
        account: "",
        collectDatetime: "",
        value: "",
        unitNo: "",
        dataTypeNames: "",
      },
      //   数据项
      dataItemList: [],
      departmentList: [],
      postList: [],
      staffList: [],
      // 批量删除
      nowselectedList: [],
      // 单位列表
      unitlist: [],
      isInputFlag: true,
      // TODO:
      searchlist: {
        facilityNo: "",
        dataName: "",
      },
    };
  },
  watch: {},
  created() {},
  mounted() {
    this.getTableData();
    this.getselecltlist();
    // TODO:
    this.loading = true;
  },
  methods: {
    // 手动添加
    async userAdd() {
      this.isInputFlag = !this.isInputFlag;
      if (this.formData.dataTypeNames) {
        if (this.isInputFlag) {
          let params = {
            dataTypeName: this.formData.dataTypeNames,
            isManualEntry: true,
          };
          let res = await Api.addItem(params);
          if (res.code === 1) {
            this.$message.success("手动添加物联数据项成功！");
            this.queryItem();
          } else {
            this.$message.error("手动添加物联数据项失败！");
          }
        }
      } else {
        this.isInputFlag = false;
        this.$message.warning("物联数据不能为空！");
      }
    },
    // 获取表格数据
    async getTableData(facilityNo = "", dataName = "") {
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: {
          facilityNo,
          dataTypeName: dataName,
          organizationNo: sessionStorage.getItem("organizationNo"),
        },
      };
      this.entity = params.entity;
      let res = await Api.queryPageCondition(params);
      this.loading = false;
      this.tableData = res.data.content;
      if (this.tableData.length === 0 && this.currentPage > 1) {
        this.currentPage--;
        this.getTableData();
      }
      this.totalSize = res.data.totalElements;
    },
    // 获取下拉选择数据
    async getselecltlist() {
      let params = {
        organizationList: sessionStorage
          .getItem("organizationList")
          .split(",")
          .concat([sessionStorage.parentId || ""]),
        farmingTypeNo: sessionStorage.getItem("farmingTypeNo"),
        facilityStatus: false,
      };
      // 获取设施
      userreq.getfacilityAll(params).then((res) => {
        this.facilityList = res.data;
        this.formConfig[0].options = res.data;
      });
      // 获取单位
      danwei
        .getallBasicunitlist({ unitTypeNo: "1001492117000847360" })
        .then((res) => {
          this.unitlist = res.data;
        });
      //   获取录入人
      managementtwo.getEmployeeList().then((res) => {
        if (res.code !== 1) {
          return;
        }
        this.staffList = res.data;
      });
      // 获取数据项
      this.queryItem();
    },
    async queryItem() {
      let res = await Api.queryItem();
      this.dataItemList = res.data;
    },
    // TODO:选择设施
    async selectFacility(e) {
      this.dataItemList = [];
      this.formData = {
        facilityNo: e,
      };
      // 获取数据项
      let params = {
        facilityNo: e,
        organizationNo: sessionStorage.getItem("organizationNo"),
        visible: true,
      };
      let res = await Api.getDataItem(params);
      this.dataItemList = res.data;
    },
    // 添加
    add() {
      this.textTitle = "添加";
      this.dialogFormVisible = true;
      this.addActive = false;
      this.formData = {};
      this.queryItem();
    },
    // 修改
    edit(row) {
      this.textTitle = "编辑";
      this.dialogFormVisible = true;
      this.formData = { ...row };
      console.log(this.formData, "kk");
      this.formData.environmentalDataId = row.environmentalDataId;
    },
    save() {
      this.$refs.formData.validate(async (valid) => {
        if (valid) {
          let params = {
            ...this.formData,
          };
          params["organizationNo"] = sessionStorage.getItem("organizationNo");
          if (this.formData.account && this.formData.account.person) {
            params["account"] = this.formData.account.person.name;
          }
          this.dataItemList.forEach((el) => {
            if (el.dataTypeConfigId === this.formData.dataTypeConfigId) {
              params["dataTypeName"] = el.dataTypeName;
            }
          });
          this.facilityList.forEach((el) => {
            if (el.facilityNo === this.formData.facilityNo) {
              params["facilityName"] = el.facilityName;
            }
          });
          delete params["departmentNo"];
          if (this.textTitle == "添加") {
            let res = await Api.add(params);
            if (res.code === 1) {
              this.addActive = true;
              this.dialogFormVisible = false;
              this.$message.success("数据录入成功！");
              this.cancel();
              this.getTableData();
            } else {
              this.$message.error("数据录入失败！");
            }
          } else {
            // console.log(this.formData); return
            let res = await Api.edit(params);
            console.log(res, "whw");
            if (res.code === 1) {
              this.$message.success("修改成功！");
              // this.dialogFormVisible = false;
              this.cancel();
              this.getTableData();
            } else {
              this.$message.error("修改失败！");
            }
          }
        } else {
          return false;
        }
      });
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.getTableData(this.searchlist.facilityNo, this.searchlist.dataName);
    },
    changeCurrentPage(currentPage) {
      this.currentPage = currentPage;
      this.getTableData(this.searchlist.facilityNo, this.searchlist.dataName);
    },
    // 单个删除
    del(row) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(async () => {
          let res = await Api.del(row.environmentalDataId);
          if (res.code === 1) {
            this.$message.success("删除成功");
            this.getTableData();
          } else {
            this.$message.error("删除失败");
          }
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    // 批量删除
    handlerDel() {
      console.log(this.nowselectedList);
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass",
      })
        .then(async () => {
          let res = await Api.dels(this.nowselectedList);
          if (res.code === 1) {
            this.$message.success("批量删除成功");
            this.getTableData();
          } else {
            this.$message.error("批量删除失败");
          }
        })
        .catch(() => {
          this.$message("取消删除");
        });
    },
    cancel() {
      this.isInputFlag = true;
      this.formData = {};
      this.dataItemList = [];
      this.$nextTick(() => {
        // this.$refs.formData.resetFields();
        this.$refs.formData.clearValidate();
      });
      this.dialogFormVisible = false;
      this.addActive = true;
      this.delActive = false;
    },
    handleSelectionChange(list) {
      this.nowselectedList = [];
      this.nowselectedList = list.map((item) => {
        return item.environmentalDataId;
      });
      if (this.nowselectedList && this.nowselectedList.length > 0) {
        this.delActive = true;
      } else this.delActive = false;
    },
    // TODO:
    // 排序
    changeTableSort(column) {
      this.sortList = column.order
        ? [
            {
              property: column.prop,
              direction: column.order == "ascending" ? "asc" : "desc",
            },
          ]
        : [];
      this.getTableData();
    },
    // 导出
    async download() {
      let params = {
        entity: {
          ...this.entity,
        },
      };
      let url = "v3/iot/environmentalData/download";
      let excel = "环境数据录入";
      this.downloadExcel(url, params, excel);
    },
    search(e) {
      this.currentPage = 1;
      this.searchlist = { ...e };
      this.getTableData(e.facilityNo, e.dataName);
    },
  },
};
</script>
  <style lang="scss" scoped>
.zhtabletitle {
  color: #31f7dd;
  margin-bottom: 10px;
}
::v-deep .tab-select {
  width: 100%;
  .butt-list-sty {
    position: absolute;
    left: 5px;
    top: 7px;
  }
}
</style>
  